<template>
    <div class="ep-prove">
        <div class="ep-prove-file" @click="upload">
            <img v-if="fileUrl" :src="fileUrl" />
            <input type="file" accept="image/*" @change="fileChanged" ref="file" multiple="multiple" style="display: none;">
        </div>   
    </div>
</template>

<script>
export default {
    props: {
        file: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            fileUrl: ''
        }
    },
    methods: {
        upload() {
            this.$refs.file.click()
        },
        fileChanged() {
            let self = this
            const list = this.$refs.file.files;

            if (list.length > 1) {
                this.$toast({
                    message: `最多只能选择1张图片。`,
                    duration: 3000
                });
                return
            }
            
            const formData = new FormData();
            formData.append("files", list[0]);
            const xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', this.uploadProgress, false)
            xhr.open('POST', 'http://61.153.183.140:9204/hzsb_zw/app/img/upload', true)
            xhr.send(formData)
            xhr.onload = () => {
                if (xhr.status === 200 || xhr.status === 304) {
                    let data = JSON.parse(xhr.response);
                    if (data.success) {
                        // self.imgList.push(item)
                        self.fileUrl = data.body[0]
                        self.$emit('uploadSuccess', data.body[0]);
                    } else {
                        this.$toast({
                            message: `上传图片失败`,
                            duration: 3000
                        });
                    }
                } else {
                    console.log(`error：error code ${xhr.status}`)
                }
            }
            
            this.$refs.file.value = ''
        }
    }
}
</script>


<style lang="less" scoped>
.ep-prove {
    width: 100%;
    .ep-prove-file {
        width: 100%;
        height: 100%;
        img {
            width: 100%;
            height: 100%;
        }
    }
}
</style>

